/*
 * Copyright (C) 2015 kmy-framework-base Project
 *               Author: Administrator
 *               Date: 2015年11月4日
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.zmq.ha.client.listner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.rabbitmq.client.ShutdownListener;
import com.rabbitmq.client.ShutdownSignalException;
import com.zmq.ha.client.core.ChannelWrapper;
import com.zmq.ha.client.core.ConnectionWrapper;

public class MyChannelShutdownListener implements ShutdownListener {
	
	private final static Logger logger = LoggerFactory.getLogger(MyChannelShutdownListener.class);
	
	final ChannelWrapper channelWrapper;
	
	public MyChannelShutdownListener(ChannelWrapper channelHandler) {
		super();
		this.channelWrapper = channelHandler;
	}


	@Override
	public void shutdownCompleted(ShutdownSignalException cause) {
		channelWrapper.channelShutdown();
		
		if( !cause.isInitiatedByApplication() ){
			//TODO  recovery connection...
			channelWrapper.getConnectionWrapper().isRecovery = true;
			ConnectionWrapper.COMSUMER_EXECUTRO.execute(new Runnable() {
				@Override
				public void run() {
					// TODO Auto-generated method stub
					logger.info("RMQ : occur connectionShutDown, begin recovering channel...");
					try {
						channelWrapper.recoverChannel(false);
					} catch (Exception e) {
						logger.info("RMQ : occur connectionShutDown, recovering channel error...");
						e.printStackTrace();
					}
				}
			});
			
		} else{
			logger.info("RMQ : normal exit");
		}
	}

}
